//
//  WMCroppingImagesViewController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/11.
//

import UIKit

class WMCroppingImagesViewController: WMBaseViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    
    var image: UIImage?
    var cropOverlay: WMCropOverlayView!
    var popBlock: ((UIImage)->Void)?
    var currentDragType: CropDragType = .none
    
    // 添加一个容器视图来替代原来的 scrollView
    var imageContainerView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imageView.image = image
        imageView.contentMode = .scaleAspectFit // 确保图片按比例显示
        customNavBar.setTitle("裁剪图片")
        setupUI()
        setupGestures()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        updateLayout()
    }
    
    func setupUI() {
        // 创建容器视图
        imageContainerView = UIView()
        imageContainerView.clipsToBounds = true
        view.insertSubview(imageContainerView, belowSubview: imageView)
        
        // 设置 imageView 为容器视图的子视图
        imageView.removeFromSuperview()
        imageContainerView.addSubview(imageView)
        // 关闭自动布局，使用手动 frame，避免被约束错误影响导致显示不完整
        imageView.translatesAutoresizingMaskIntoConstraints = true
        // 确保不裁剪内部内容，由 contentMode 控制等比缩放以完整展示
        imageView.clipsToBounds = false
        
        // 初始化裁剪覆盖层
        cropOverlay = WMCropOverlayView(frame: imageContainerView.frame)
        cropOverlay.isUserInteractionEnabled = false
        view.addSubview(cropOverlay)
    }
    
    func updateLayout() {
        // 设置容器视图的frame，考虑导航栏和安全区域
        let safeArea = view.safeAreaLayoutGuide.layoutFrame
        let containerY = customNavBar.frame.maxY + 20
        let containerHeight = view.frame.height - containerY - 120
        
        imageContainerView.frame = CGRect(
            x: 20,
            y: containerY,
            width: view.frame.width - 40,
            height: containerHeight
        )
        
        cropOverlay.frame = imageContainerView.frame
        updateImageFrame()
    }
    
    func updateImageFrame() {
        guard let image = image else { return }
        
        let imageSize = image.size
        let containerSize = imageContainerView.bounds.size
        
        // 计算适合容器视图的图片尺寸，保持宽高比 (Aspect Fit)
        let imageAspectRatio = imageSize.width / imageSize.height
        let containerAspectRatio = containerSize.width / containerSize.height
        
        var targetSize: CGSize
        
        if imageAspectRatio > containerAspectRatio {
            // 图片比容器宽，以宽度为基准缩放
            let scale = containerSize.width / imageSize.width
            targetSize = CGSize(width: containerSize.width,
                                height: imageSize.height * scale)
        } else {
            // 图片比容器高，以高度为基准缩放
            let scale = containerSize.height / imageSize.height
            targetSize = CGSize(width: imageSize.width * scale,
                                height: containerSize.height)
        }
        
        // 设置 imageView 的 frame，确保图片完整显示并居中
        imageView.frame = CGRect(
            x: (containerSize.width - targetSize.width) / 2,
            y: (containerSize.height - targetSize.height) / 2,
            width: targetSize.width,
            height: targetSize.height
        )
        
        print("容器尺寸: \(containerSize)")
        print("图片原始尺寸: \(imageSize)")
        print("目标尺寸: \(targetSize)")
        print("imageView frame: \(imageView.frame)")
        
        updateCropOverlay()
    }
    
    func updateCropOverlay() {
        guard let image = image else { return }
        
        // 确保裁剪框在图片范围内
        let imageFrameInOverlay = imageContainerView.convert(imageView.frame, to: cropOverlay)
        
        // 计算初始裁剪框大小（基于图像大小）
        let imageAspectRatio = image.size.width / image.size.height
        let initialCropSize: CGSize
        
        // 使用图片实际显示尺寸的80%作为初始裁剪框
        let cropSizeRatio: CGFloat = 0.95
        
        if imageAspectRatio > 1 {
            // 宽图
            initialCropSize = CGSize(
                width: imageFrameInOverlay.width * cropSizeRatio,
                height: imageFrameInOverlay.width * cropSizeRatio / imageAspectRatio
            )
        } else {
            // 高图或方图
            initialCropSize = CGSize(
                width: imageFrameInOverlay.height * cropSizeRatio * imageAspectRatio,
                height: imageFrameInOverlay.height * cropSizeRatio
            )
        }
        
        // 确保裁剪框不超过图片边界
        let finalCropSize = CGSize(
            width: min(initialCropSize.width, imageFrameInOverlay.width),
            height: min(initialCropSize.height, imageFrameInOverlay.height)
        )
        
        // 居中放置裁剪框
        let cropX = imageFrameInOverlay.midX - finalCropSize.width / 2
        let cropY = imageFrameInOverlay.midY - finalCropSize.height / 2
        
        cropOverlay.cropRect = CGRect(
            x: cropX,
            y: cropY,
            width: finalCropSize.width,
            height: finalCropSize.height
        )
        cropOverlay.setNeedsDisplay()
    }
    
    // MARK: - Gesture Setup
    func setupGestures() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        cropOverlay.addGestureRecognizer(panGesture)
        cropOverlay.isUserInteractionEnabled = true
        
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        cropOverlay.addGestureRecognizer(pinchGesture)
        
        // 添加双击手势来重置裁剪框
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
        doubleTapGesture.numberOfTapsRequired = 2
        imageContainerView.addGestureRecognizer(doubleTapGesture)
    }
    
    // MARK: - Gesture Handlers
    @objc func handlePan(_ gesture: UIPanGestureRecognizer) {
        let location = gesture.location(in: cropOverlay)
        
        if gesture.state == .began {
            currentDragType = cropOverlay.hitTest(point: location)
        }
        
        let translation = gesture.translation(in: view)
        
        var newRect = cropOverlay.cropRect
        
        switch currentDragType {
        case .move:
            newRect.origin.x += translation.x
            newRect.origin.y += translation.y
        case .topLeft:
            newRect.origin.x += translation.x
            newRect.origin.y += translation.y
            newRect.size.width -= translation.x
            newRect.size.height -= translation.y
        case .topRight:
            newRect.origin.y += translation.y
            newRect.size.width += translation.x
            newRect.size.height -= translation.y
        case .bottomLeft:
            newRect.origin.x += translation.x
            newRect.size.width -= translation.x
            newRect.size.height += translation.y
        case .bottomRight:
            newRect.size.width += translation.x
            newRect.size.height += translation.y
        case .top:
            newRect.origin.y += translation.y
            newRect.size.height -= translation.y
        case .bottom:
            newRect.size.height += translation.y
        case .left:
            newRect.origin.x += translation.x
            newRect.size.width -= translation.x
        case .right:
            newRect.size.width += translation.x
        case .none:
            return
        }
        
        // 约束检查（确保不超出图像边界且最小尺寸）
        let imageFrameInOverlay = imageContainerView.convert(imageView.frame, to: cropOverlay)
        if newRect.minX >= imageFrameInOverlay.minX &&
            newRect.maxX <= imageFrameInOverlay.maxX &&
            newRect.minY >= imageFrameInOverlay.minY &&
            newRect.maxY <= imageFrameInOverlay.maxY &&
            newRect.width >= 50 && newRect.height >= 50 {
            cropOverlay.cropRect = newRect
        }
        
        gesture.setTranslation(.zero, in: view)
        cropOverlay.setNeedsDisplay()
        
        if gesture.state == .ended {
            currentDragType = .none
        }
    }
    
    @objc func handlePinch(_ gesture: UIPinchGestureRecognizer) {
        if gesture.state == .changed {
            let scale = gesture.scale
            let center = gesture.location(in: cropOverlay)
            
            var newRect = cropOverlay.cropRect
            let dx = (newRect.width * scale - newRect.width) / 2
            let dy = (newRect.height * scale - newRect.height) / 2
            
            newRect = newRect.insetBy(dx: -dx, dy: -dy)
            
            // Adjust center
            newRect.origin.x -= (center.x - newRect.midX) * (scale - 1)
            newRect.origin.y -= (center.y - newRect.midY) * (scale - 1)
            
            // Constrain to image bounds
            let imageFrameInOverlay = imageContainerView.convert(imageView.frame, to: cropOverlay)
            if newRect.minX >= imageFrameInOverlay.minX &&
                newRect.maxX <= imageFrameInOverlay.maxX &&
                newRect.minY >= imageFrameInOverlay.minY &&
                newRect.maxY <= imageFrameInOverlay.maxY &&
                newRect.width >= 50 && newRect.height >= 50 {
                cropOverlay.cropRect = newRect
                cropOverlay.setNeedsDisplay()
            }
            
            gesture.scale = 1.0
        }
    }
    
    @objc func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
        // 双击重置裁剪框到初始大小和位置
        updateCropOverlay()
    }
    
    //删除手势点击事件
    @IBAction func deleteTapGesture(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    //确定手势点击事件 - 裁剪图片
    @IBAction func sureTapGesture(_ sender: Any) {
        // Crop the image
        guard let croppedImage = cropImage() else { return }
        
        if((self.popBlock) != nil){
            self.popBlock!(croppedImage)
        }
        navigationController?.popViewController(animated: true)
    }
    
    // MARK: - Image Cropping
    func cropImage() -> UIImage? {
        guard let image = image else { return nil }
        
        // 转换为图像坐标系
        let cropRect = convertCropRectToImageCoordinates()
        
        print("原始图像大小: \(image.size)")
        print("裁剪区域 (图像坐标): \(cropRect)")
        print("图像视图框架: \(imageView.frame)")
        
        // 确保裁剪区域在图像范围内
        let boundedRect = cropRect.intersection(CGRect(origin: .zero, size: image.size))
        
        guard !boundedRect.isEmpty, boundedRect.width > 0, boundedRect.height > 0 else {
            print("裁剪区域无效")
            return nil
        }
        
        // 执行裁剪
        guard let cgImage = image.cgImage?.cropping(to: boundedRect) else {
            return nil
        }
        
        return UIImage(cgImage: cgImage, scale: image.scale, orientation: image.imageOrientation)
    }
    
    func convertCropRectToImageCoordinates() -> CGRect {
        // 将裁剪框从 overlay 坐标系转换到 imageView 坐标系
        let cropRectInImageView = cropOverlay.convert(cropOverlay.cropRect, to: imageView)
        
        // 转换为图像坐标系
        guard let image = image else { return cropRectInImageView }
        
        let imageSize = image.size
        let imageViewSize = imageView.bounds.size
        
        // 计算图像在 imageView 中的实际显示区域（考虑 aspect fit）
        let scale: CGFloat
        let imageRect: CGRect
        
        let imageAspectRatio = imageSize.width / imageSize.height
        let viewAspectRatio = imageViewSize.width / imageViewSize.height
        
        if imageAspectRatio > viewAspectRatio {
            // 图片比视图宽
            scale = imageViewSize.width / imageSize.width
            let scaledHeight = imageSize.height * scale
            imageRect = CGRect(
                x: 0,
                y: (imageViewSize.height - scaledHeight) / 2,
                width: imageViewSize.width,
                height: scaledHeight
            )
        } else {
            // 图片比视图高
            scale = imageViewSize.height / imageSize.height
            let scaledWidth = imageSize.width * scale
            imageRect = CGRect(
                x: (imageViewSize.width - scaledWidth) / 2,
                y: 0,
                width: scaledWidth,
                height: imageViewSize.height
            )
        }
        
        // 计算在图像坐标系中的裁剪区域
        let scaleFactor = 1.0 / scale
        let xInImage = (cropRectInImageView.origin.x - imageRect.origin.x) * scaleFactor
        let yInImage = (cropRectInImageView.origin.y - imageRect.origin.y) * scaleFactor
        let widthInImage = cropRectInImageView.width * scaleFactor
        let heightInImage = cropRectInImageView.height * scaleFactor
        
        return CGRect(
            x: max(0, xInImage),
            y: max(0, yInImage),
            width: min(imageSize.width, widthInImage),
            height: min(imageSize.height, heightInImage)
        )
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        updateImageFrame()
    }
}
